package model.data.database;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import model.Order;
import model.data.OrderStore;

public class OrderTable implements OrderStore {
	/* Handles requests to the database */
	DatabaseHandler dbHandler;
	
	/** Constructs a new category table */
	public OrderTable() {
		this.dbHandler = new DatabaseHandler();
	}
	
	
	@Override
	public void write(Order order) throws Exception {
		this.dbHandler.callUpdateProcedure("sp_insertorder(?,?)", order.getId(), order.getOrderDate());

	}

	
	@Override
	public void update(Order order) {
		// TODO Auto-generated method stub\
	}

	
	@Override
	public void delete(Order order) throws Exception {
		this.dbHandler.callUpdateProcedure("sp_deleteorder(?)", order.getId());

	}

	
	@Override
	public int getCount() throws Exception {
		int count = 0;
		ArrayList<DataRecord> records;

		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getcountorder");
		
		// Fill list
		for (DataRecord dr : records) {
			count = Integer.parseInt(dr.getValue("Result"));
		}
		
		// Return result
		return count;
	}

	
	@Override
	public List<Order> getById(long id) throws Exception {
		ArrayList<Order> orders;
		ArrayList<DataRecord> records;
		
		// Get records
		records = (ArrayList<DataRecord>)this.dbHandler.callQueryProcedure("sp_getbyidorder(?)", id);
		
		// Create list
		orders = new ArrayList<Order>();
		
		// Fill list
		//TODO update
		for (DataRecord dr : records) {
			Order order = new Order();
			order.setId(Integer.parseInt(dr.getValue("OrderId")));
			order.setCustomerId(Long.parseLong(dr.getValue("CustomerId")));
			order.setOrderDate(new Date(dr.getValue("OrderDate")));
			orders.add(order);
		}
		
		// Return result
		return orders;
	}
}
